/* Queue class implementation in c.  Uses linked lists and malloc for queue creation/modification.

   Source code taken from : http://en.wikipedia.org/wiki/Queue_%28data_structure%29#Example_using_C

*/


#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include "includes.h"
 
struct queue_node
{
  struct queue_node *next;     
  struct proc_info *data;
};

struct queue
{
  struct queue_node *first;
  struct queue_node *last;
};

int enqueue(struct queue *q, struct proc_info *value)
{
  struct queue_node *node = malloc(sizeof(struct queue_node));
  if (node == NULL) {
    errno = ENOMEM;
    return 1;
  }
  node->data = value;

  if (q->first == NULL) {
    q->first = q->last = node;
  } else {
    q->last->next = node;
    q->last = node;
  }
  node->next = NULL;
  return 0;
}
 
struct proc_info* dequeue(struct queue *q)
{
  struct proc_info* value;
  struct queue_node *tmp;

  /* Check for empty queue */
  if (!q->first) {
    return NULL;
  }

  value = q->first->data;

  tmp = q->first;
  /* Restructure queue */
  if (q->first == q->last) {
    q->first = q->last = NULL;
  } else {
    q->first = q->first->next;
  }
  free(tmp);
  return value;
}
 
void init_queue(struct queue *q)
{
  q->first = q->last = NULL;
}
 
int queue_empty_p(const struct queue *q)
{
  return q->first == NULL;
}
